package com.itheima.health.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.pojo.User;
import com.itheima.health.pojo.UserDto;
import com.itheima.health.service.MobbileService;
import com.itheima.health.service.SetMealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.builder.BuilderException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 移动端Controller
 */
@RestController
@Slf4j
@RequestMapping("/mobile")
public class MobbileController {
    @Autowired
    private MobbileService mobbileService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SetMealService setMealService;

    String yzm = "";
    /**
     * 验证码发送
     *
     * @param type
     * @param telephone
     * @return
     */
    //MOBILE_SIGNIN移动端登录类型
    @PostMapping("/validateCode/send")
    public Result send(@RequestParam String type, @RequestParam Long telephone) {
        log.info("验证码类型：{},电话:{}", type, telephone);
        Random random = new Random();
        //String yzm = "";
        for (int i = 0; i < 4; i++) {
            int yiwei = random.nextInt(9) + 1;
            yzm += yiwei;
        }
        log.info("yzm:{}", yzm);
        //把验证码放入Redis缓存
        redisTemplate.opsForValue().set(telephone+"",yzm,2, TimeUnit.MINUTES);

        return new Result(true, "验证码发送成功");
    }

    /**
     * 前端登录
     */
    @PostMapping("/login/smsLogin")
    @Transactional
    public Result login(@RequestBody UserDto Message,HttpSession session) {
        log.info("接收到前台的信息:{}", Message);
        //System.out.println(yzm);
        //从Redis中获取验证码
        Object RedisCode= redisTemplate.opsForValue().get(Message.getTelephone());
        String code = Message.getValidateCode();
        if (code!=null&&code.equals(RedisCode)&&Message.getValidateCode().length()==4) {
            LambdaQueryWrapper<Member> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Member::getPhoneNumber, Message.getTelephone());
            //从数据库中获取符合条件的用户
            Member dbUser = mobbileService.getOne(wrapper);
            //如果没有则为用户创建
            if (dbUser == null) {
                Member member = new Member();
                member.setPhoneNumber(Message.getTelephone());
                //member.setFileNumber(Message.getTelephone());
                //Integer id = user.getId();
                //mobbileService.addUserRole(id);
                dbUser = member;

               mobbileService.saveMember(dbUser);
                session.setAttribute("dbuser", dbUser.getId());
            }
            session.setAttribute("dbuser", dbUser.getId());
            redisTemplate.delete(Message.getTelephone());
            return new Result(true, "登录成功");
        } else {
            return new Result(false, "验证码错误登录失败");
        }

    }
    @GetMapping("setmeal/findById")
    public Result findById(Integer id) {
        Setmeal selectById = setMealService.selectById(id);
        return new Result(true, MessageConst.QUERY_SETMEAL_SUCCESS, selectById);
    }
    @GetMapping("/setmeal/getSetmeal")
    public Result selectSetmeal() {
        List<Setmeal> all = setMealService.findAll();
        return new Result(true, MessageConst.QUERY_SETMEALLIST_SUCCESS, all);
    }
}
